﻿CREATE PROCEDURE [dbo].[AccountBalance]
(
	@AccountIds NVARCHAR(500),
	@AtTIme DATETIME
)
AS
BEGIN
	SELECT SUM(Debits) - SUM(Credits) FROM (

		SELECT Amount AS Debits, 0 AS Credits, TransactionId FROM TransactionDebits
		WHERE @AccountIds LIKE '%,' + CONVERT(NVARCHAR, AccountId) + ',%'
	UNION
		SELECT 0 AS Debits, Amount AS Credits, TransactionId FROM TransactionCredits
		WHERE @AccountIds LIKE '%,' + CONVERT(NVARCHAR, AccountId) + ',%'

	) p JOIN Transactions t ON p.TransactionId = Id
	WHERE t.Date <= @AtTIme
END